package Socket1;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UdpEchoClient {

    private DatagramSocket socket;
    private int port;
    private String serverIp;

    public UdpEchoClient(int port, String serverIp) throws SocketException {
        this.socket = new DatagramSocket();
        this.port = port;
        this.serverIp = serverIp;
    }

    public void  start() throws Exception{
        Scanner in=new Scanner(System.in);
        while (true){
            System.out.println("请输入要发送的内容： ");
            if (!in.hasNext())break;
            String str=in.nextLine();
            DatagramPacket requestpacket=new DatagramPacket(str.getBytes(),str.getBytes().length,
                    InetAddress.getByName(serverIp),port);
            socket.send(requestpacket);

            DatagramPacket reponsePacket=new DatagramPacket(new byte[1024],1024);
            socket.receive(reponsePacket);
            String responseStr=new String(reponsePacket.getData(),0,reponsePacket.getLength());
            System.out.println(responseStr);
        }
    }

    public static void main(String[] args) throws Exception {
        UdpEchoClient client=new UdpEchoClient(8888,"127.0.0.1");
        client.start();
    }

}
